﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Pro.Common.IoC
{
    public class DependencyRegistry : ComponentRegistry
    {
        private readonly ITypeSource _typeSource;

        public DependencyRegistry(ITypeSource typeSource)
        {
            _typeSource = typeSource;
        }

        public override void Configure(IComponentContainerConfigurator componentContainerConfigurator)
        {
            IEnumerable<Type> types = _typeSource.GetTypes();
            foreach (Type type in types)
            {
                object[] dependencyAttributes = type.GetCustomAttributes(typeof (DependencyAttribute), false);
                if (dependencyAttributes.Any())
                {
                    foreach (DependencyAttribute dependencyAttribute in dependencyAttributes)
                    {
                        switch (dependencyAttribute.ComponentInstanceScope)
                        {
                            case ComponentInstanceScope.Transient:
                            case ComponentInstanceScope.PerRequest:
                            case ComponentInstanceScope.Singleton:
                                break;
                            default:
                                throw new NotSupportedException();
                        }
                        componentContainerConfigurator.RegisterType(dependencyAttribute.ServiceType, type,
                            dependencyAttribute.Key);
                    }
                }
            }
        }
    }
}